package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.ofc.api.dto.SoHeadDTO;
import com.lsh.ofc.api.service.SoService;
import com.lsh.oms.core.email.SendEmailService;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.model.order.OrderSignDetail;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.core.model.push.ordersign.OrderSignItemsInfo;
import com.lsh.oms.core.model.push.ordersign.OrderSignPushForm;
import com.lsh.oms.core.proxy.service.WgOrderSignPushProxy;
import com.lsh.oms.core.service.other.ShippingOrderService;
import com.lsh.oms.core.service.other.SignOrderService;
import com.lsh.oms.core.utils.DateUtil;
import com.lsh.oms.worker.service.base.OmsSimpleElasticJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author miaozhuang
 * @date 18/5/16
 * 签收单数据push同步
 * <p>
 * 1:oms_TASK获取签收单ID,根据签收单ID 获取Order_SIGN_HEAD,发送 订单号Orderid 通过ofc接口获取   [so_id,supplyid]列表
 * 2:根据 supplyid,so_id 过滤 Order_SIGN_DETAIL
 * 3:其他:第一步 获取获取几条  发送几条push,具体的push地址根据supplierid适配具体URL
 * <p>
 * <p>
 * <p>
 * 注意:
 * 1:签收单接口的用  发货单的arrived_at
 * 2:定损的的arrived_at用order_ro_head.pass_at
 */
@Deprecated
@Slf4j
public class OrderReceiptPushTask extends OmsSimpleElasticJob {

    @Autowired
    private SignOrderService signOrderService;

    @Autowired
    private WgOrderSignPushProxy wgOrderSignPushProxy;

    @Autowired
    private SoService soService;

    @Autowired
    private ShippingOrderService shippingOrderService;

    @Autowired
    private OrderPushUrlInfo orderPushUrlInfo;

    @Autowired
    private SendEmailService sendEmailService;


    @Override
    protected Integer getFetchSize() {
        return 100;
    }

    @Override
    protected TaskType getTaskType() {
        return TaskType.Bill_SIGN;
    }

    @Override
    protected List<Integer> dealTaskStatus() {

        return Arrays.asList(TaskStatus.TASK_UN_DEAL.getCode(), TaskStatus.TASK_DEAL_FAIL.getCode());
    }

    @Override
    protected int process(OmsTask omsTask) {

        OrderSignHead orderSignHead = this.signOrderService.getSignHead(Long.parseLong(omsTask.getRefCode()), true);
        //大KA处理  : 没有OFC相关数据
        //1 常温  2 冻品
        int storege_type = orderSignHead.getStorageTypeId();
        if (storege_type != 1) {

            log.info("签收单:冻品签收单数据不同步,签收单ID:" + orderSignHead.getShippingOrderId());
            return 1;
        }
        //机构与so关系
        HashMap<Integer, String> soSupplyOrg = this.getOfcSoSupplyOrg(orderSignHead);
        //签收单详情拆单结果
        HashMap<Integer, List<OrderSignDetail>> orderSignDetailSplit4org = new HashMap<>();
        //签收单总额
        BigDecimal order_price = this.orderSignDetailSplit4org(orderSignHead.getDetails(), orderSignDetailSplit4org);

        for (Map.Entry<Integer, List<OrderSignDetail>> orgEntry : orderSignDetailSplit4org.entrySet()) {
//            Integer supplyOrg = orgEntry.getKey();

            String data = JSON.toJSONString(this.orderSignPushFormBuilder(orgEntry, orderSignHead, soSupplyOrg, order_price));
            //根据SuppliorId获取推送地址
            String pushUrl = this.orderPushUrlInfo.getPushUrl();
            String responseData = this.wgOrderSignPushProxy.push(pushUrl + "/api/so/receipt", data, orderSignHead.getVenderId());

            JSONObject jsonObjectResponse = JSON.parseObject(responseData);
            int ret = jsonObjectResponse.getInteger("ret").intValue();

            if (ret != 0) {
                String msg = jsonObjectResponse.getString("msg");
                log.info("签收单推送失败 msg is " + msg);
//                this.sendEmail(orderSignHead.getReceiptOrderId(), msg);
                return -1;
            }
        }

        return 1;
    }

    /**
     * 处理失败邮件发送
     *
     * @param orderReceiptId 签收单号
     * @param msg            错误信息
     */
    private void sendEmail(Long orderReceiptId, String msg) {
        if (msg.length() > 200) {
            msg = msg.substring(0, 200);
        }
        String message = orderReceiptId + " 签收单推送失败 " + msg;

        this.sendEmailService.asyncSendEmail(message, "签收单进销存推送失败-" + DateUtil.formatTime(new Date()));
    }

    /**
     * 查询so与机构关系
     *
     * @param orderSignHead 签收单信息
     * @return so与结构关系map
     */
    private HashMap<Integer, String> getOfcSoSupplyOrg(OrderSignHead orderSignHead) {
        //根据orderID 调用OFC接口 获取  [supplyid,so_id] 列表
        List<SoHeadDTO> soHeadDTOs = this.soService.querySignOrders(orderSignHead.getOrderId());
        HashMap<Integer, String> soSupplyOrg = new HashMap<>(4);
        // hash
        log.info("签收单:OFC接口返回的数据" + JSON.toJSONString(soHeadDTOs));
        log.info("签收单:OFC接口返回的[supplyid,so_id] 列表:");
        for (SoHeadDTO soHeadDTO : soHeadDTOs) {
            log.info("签收单:supplyid,so_id:" + soHeadDTO.getSupplierOrg() + "," + soHeadDTO.getSoCode());
            soSupplyOrg.put(soHeadDTO.getSupplierOrg(), soHeadDTO.getSoCode());
        }

        return soSupplyOrg;
    }

    /**
     * 已so为单位构建提交进销存数据
     *
     * @param orgEntry      机构与签收详情对应关系
     * @param orderSignHead 签署单信息
     * @param soSupplyOrg   机构与so对应关系
     * @param order_price   订单总金额
     * @return 提交进销存数据信息
     */
    private OrderSignPushForm orderSignPushFormBuilder(Map.Entry<Integer, List<OrderSignDetail>> orgEntry, OrderSignHead orderSignHead, HashMap<Integer, String> soSupplyOrg, BigDecimal order_price) {
//        int zone_id = orderSignHead.getZoneId();
//        String warehouseId = orderSignHead.getWarehouseId();
//        if (StringUtils.isBlank(warehouseId)) {
//            warehouseId = "";
//        }
        boolean isKA = false;
//        if (5000 == zone_id && !(warehouseId.startsWith("LS"))) {
//            isKA = true;
//            log.info("签收单:KA ORDER ,签收单ID:" + orderSignHead.getShippingOrderId());
//        }

        Integer supplyOrg = orgEntry.getKey();
        log.info("签收单:根据suppilyID进行处理,supplyOrg:" + supplyOrg);

        List<OrderSignDetail> orderSignDetails4org = orgEntry.getValue();

        OrderShippingHeadWithBLOBs orderShippingHeadWithBLOBs = this.shippingOrderService.getBolbs(orderSignHead.getOrderId());
        //获取运单抵达时间 作为签收单的到达时间
        Integer arrivedAt;
        if (orderShippingHeadWithBLOBs != null) {
            arrivedAt = orderShippingHeadWithBLOBs.getArrivedAt();
        } else {
            arrivedAt = 0;
        }
        //订单总额
        BigDecimal wg_price = BigDecimal.ZERO;
        wg_price.setScale(6);
        //按照SO_ID维度进行遍历    组装json报文  发送
        OrderSignPushForm orderSignPushForm = new OrderSignPushForm();
        List<OrderSignItemsInfo> items = new ArrayList<>();
        for (OrderSignDetail orderSignDetail : orderSignDetails4org) {
            //so_id维度汇总金额
            wg_price = wg_price.add(orderSignDetail.getMoney());

            OrderSignItemsInfo orderSignItemsInfo = new OrderSignItemsInfo();
            JSONObject jsonObjectExt = JSONObject.parseObject(orderSignDetail.getExt());
            String wm_code = (String) jsonObjectExt.get("wm_code");
            BigDecimal origin_price = jsonObjectExt.getBigDecimal("origin_price").setScale(6);
            BigDecimal saled_price = jsonObjectExt.getBigDecimal("saled_price").setScale(6);

            orderSignItemsInfo.setSale_unit(orderSignDetail.getSaleUnit());
            orderSignItemsInfo.setQty(orderSignDetail.getQty().floatValue());
            orderSignItemsInfo.setReal_qty(orderSignDetail.getRealQty().floatValue());
            orderSignItemsInfo.setGoods_name(orderSignDetail.getSkuName());
            orderSignItemsInfo.setGoods_id(wm_code);
            orderSignItemsInfo.setOrigin_price(origin_price.floatValue());
            orderSignItemsInfo.setPrice(saled_price.floatValue());
            items.add(orderSignItemsInfo);
        }
        orderSignPushForm.setItems(items);
        orderSignPushForm.setOrder_id(String.valueOf(orderSignHead.getOrderId()));
        //大KA没有OFC相关数据  没有SO_ID
        String so_id = soSupplyOrg.get(supplyOrg);
        if (so_id == null) {
            so_id = "0";
        }
        log.info("签收单:回传,so_id:" + so_id + "  supplyorid" + supplyOrg);
        if (isKA) {
            orderSignPushForm.setSo_id(null);
        } else {
            orderSignPushForm.setSo_id(so_id);
        }
        //签收单总金额=order_receipt_detail表中的 (price/sale_unit)* real_qty=折扣费用+签收金额      例如：   100
        orderSignPushForm.setOrder_price(order_price.floatValue());
        orderSignPushForm.setWg_price(wg_price.floatValue());
        orderSignPushForm.setReceipt_at(String.valueOf(orderSignHead.getReceiptAt()));
        orderSignPushForm.setArrived_at(String.valueOf(arrivedAt));
        orderSignPushForm.setReceipt_order_id(String.valueOf(orderSignHead.getReceiptOrderId()));
        orderSignPushForm.setStatus(orderSignHead.getStatus());
        orderSignPushForm.setPay_type(orderSignHead.getPayType());
        //有待确定细节  //TO DO SOMETHING>0 3,<=0 1
        orderSignPushForm.setReturn_price(orderSignHead.getAfsMoney().floatValue());
        orderSignPushForm.setPay_price(orderSignHead.getMoney().floatValue());
        orderSignPushForm.setKa_fin_code("");
        orderSignPushForm.setDriver_fin_code("");
        orderSignPushForm.setZone_id(String.valueOf(orderSignHead.getZoneId()));
        //整单折扣费用= order_receipt_detail表中的 (price/sale_unit)* real_qty  -  order_receipt_head表中的money
        orderSignPushForm.setDiscount_price(order_price.subtract(orderSignHead.getMoney()).floatValue());
        orderSignPushForm.setUser_id(String.valueOf(orderSignHead.getUid()));
        orderSignPushForm.setExt(orderSignHead.getExt());
        //是否是大KA签收单
        if (isKA) {
            orderSignPushForm.setKa_type(1);
        }
        // TODO
        Integer ownerId = supplyOrg;
        orderSignPushForm.setOwner_id(ownerId);

        return orderSignPushForm;
    }

    /**
     * 根据机构拆分签收单详情
     *
     * @param orderSignDetailList      签收单详情
     * @param orderSignDetailSplit4org 拆分结果
     * @return 签收单总金额
     */
    private BigDecimal orderSignDetailSplit4org(List<OrderSignDetail> orderSignDetailList, HashMap<Integer, List<OrderSignDetail>> orderSignDetailSplit4org) {
        BigDecimal order_price = BigDecimal.ZERO;
        order_price.setScale(6);

        for (OrderSignDetail orderSignDetail : orderSignDetailList) {
            List<OrderSignDetail> orderSignDetailList4org = orderSignDetailSplit4org.get(orderSignDetail.getSupplierOrg());
            if (orderSignDetailList4org == null) {
                orderSignDetailList4org = new ArrayList<>();
                orderSignDetailList4org.add(orderSignDetail);
                log.info("签收单:分组填充[supplyid]对应的Detail列表,supplyid:" + orderSignDetail.getSupplierOrg());
                orderSignDetailSplit4org.put(orderSignDetail.getSupplierOrg(), orderSignDetailList4org);
            } else {
                log.info("签收单:分组填充[supplyid]对应的Detail列表,supplyid:" + orderSignDetail.getSupplierOrg());
                orderSignDetailList4org.add(orderSignDetail);
            }
            //计算订单总额
            order_price = order_price.add(orderSignDetail.getPrice().divide(orderSignDetail.getSaleUnit(), 6, BigDecimal.ROUND_HALF_UP).multiply(orderSignDetail.getRealQty()));
            log.info("签收单:Price():" + orderSignDetail.getPrice() + " SaleUnit():" + orderSignDetail.getSaleUnit() + "RealQty()):" + orderSignDetail.getRealQty());
        }

        return order_price;
    }
}
